

-module( query_history ).

-author( "chenyiming" ).

-import(proplists, [get_value/2, get_value/3]).

-export([ handle/1 ]).

make_json( ResList ) ->
    Fun = fun([From, Content, Time ]) ->
        [
            {<<"from">>, From},
            {<<"content">>, Content},
            {<<"time">>,  Time}
        ]
    end,
    lists:map( Fun, ResList).

handle( Params ) ->
	GroupId =      util:a2l( get_value(<<"group_id">>,       Params) ),
	PageSeq =      util:a2l( get_value(<<"page_seq">>,       Params) ),
	PageSize =     util:a2l( get_value(<<"page_size">>,      Params) ),
	BeginTime =    util:a2l( get_value(<<"begin_time">>,     Params) ),
	EndTime =      util:a2l( get_value(<<"end_time">>,       Params) ),
    From =         util:a2l( get_value(<<"from">>,           Params,     undefined) ),
    NoImSc = " and `from` != 'imsc'  ",
    util:print("query history Gid:~p PageSeq:~p PageSize:~p BeginTime:~p EndTime:~p From:~p ~n",
               [ GroupId, PageSeq, PageSize, BeginTime, EndTime, From]),
    FromTail = 
        case util:a2l( From ) of
            "undefined" ->
                "";
            _Have ->
                " and `from` = '" ++ From ++ "' "
    end,
    BeginSeq = util:a2l( ( list_to_integer( PageSeq ) - 1) * ( list_to_integer(PageSize) ) ),
    Sql = "select   `from`,content,time from msg_info_group where `to` = '"++ GroupId ++"' and time >= " ++ BeginTime ++ " and time <= " ++ EndTime ++ NoImSc  ++  FromTail ++  " order by msg_id desc limit " ++ BeginSeq ++ ","
           ++ PageSize ++ ";",
    util:print(" Sql:~p ~n", [ Sql ]),
    case emysql:execute( log_db, Sql ) of
        {result_packet, _C, _F, VL, _E} ->
            SqlCount = " select count(*) from msg_info_group where `to` = '"++ GroupId ++ "' and time >= " ++ BeginTime ++ " and time <= " ++ EndTime ++ NoImSc ++ FromTail  ++ ";",
            {result_packet, _CC, _FC, [[ Count ]], _EC } = emysql:execute( log_db, SqlCount ),
            util:print("Res:~p Count:~p ~n", [ VL, Count ]),
	        {ok, [{<<"code">>,0}, {<<"count">>, Count},{ <<"msg_list">>, make_json(VL) } ]};
        _OthersError ->
	        {ok, [{<<"code">>, 5}, {<<"msg">>, list_to_binary( Sql ) }]}
    end.



